 //
//  HRMessageViewController.m
//  SpeedDating
//
//  Created by ISU1 on 16/12/6.
//  Copyright © 2016年 isu. All rights reserved.
//

#import "FriendViewController.h"
#import "UIImage+Extension.h"

#import "RCDChatListCell.h"
#import "RCDHttpTool.h"
#import "HQConversationViewController.h"

#import "FriendLineViewController.h"
#import "FriendViewController.h"


#import "SDContactsTableViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "FriendLineViewController.h"
#import "FriendLikeMeViewController.h"


#import <objc/runtime.h>




@interface FriendViewController ()<CLLocationManagerDelegate, UITableViewDelegate, UITableViewDataSource>
{
    CGFloat longitude;
    CGFloat latitude;
}

@property (strong, nonatomic) CLLocationManager * locationManger;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, weak) UIView *navBarView;

@property (nonatomic, strong) UIView *headView;

@property (nonatomic, strong) NSDictionary *mfDic;
@property (nonatomic, strong) NSDictionary *mfDicCount;//最新状态个数
@property (nonatomic, strong) UILabel *friendCount;

@property (nonatomic, strong) RCConversationModel *noticeModel;

@property (nonatomic, strong) UILabel *countLabel;

@property (nonatomic, strong) UIImageView *likeImageView;

@property (nonatomic, strong) UIImageView *friendImage;

@property (nonatomic, strong) NSNumber *UserTypehidden;

@end

@implementation FriendViewController

- (id)init {
    self = [super init];
    if (self) {
        [self setDisplayConversationTypes:@[@(ConversationType_GROUP),@(ConversationType_PRIVATE),@(ConversationType_DISCUSSION),@(ConversationType_CHATROOM)]];
        [self setConversationAvatarStyle:RC_USER_AVATAR_CYCLE];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(outMassgUserInit) name:@"outMassgUser" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveMessage) name:@"KNOTIFICATION_ReceiveMessage" object:nil];

    [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage createImageWithColor:[UIColor clearColor]] forBarMetrics:UIBarMetricsDefault];
    [self.view addSubview:self.navBarView];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 35, 35);
    [button setImage:[UIImage imageNamed:@"message_address_list_icon"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(clickRitghButton) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:button];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth/2, 35)];
    UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth/2, 20)];
    
    titleLab.font =FontP(18);
    titleLab.textColor = [UIColor blackColor];
    titleLab.text = @"消息";
    titleLab.textAlignment = NSTextAlignmentCenter;
    [titleView addSubview:titleLab];
    
    UILabel *whithView = [[UILabel alloc] initWithFrame:CGRectMake(titleLab.centerX-8.5, titleLab.bottom+4, 17, 2)];
    whithView.backgroundColor = [UIColor whiteColor];
    [titleView addSubview:whithView];
    self.navigationItem.titleView = titleView;
    
    [self didLocation];
    [self getNotice];

    [self setUpConversationTable];
    [self setHistoryNoticeModel];
    
    

    [self.conversationListTableView reloadData];

}

- (void)receiveMessage {
    
    int count =[[RCIMClient sharedRCIMClient] getTotalUnreadCount] ;
    NSString *strCount = [NSString stringWithFormat:@"%d",[[RCIMClient sharedRCIMClient] getTotalUnreadCount] ] ;
    if (count > 0) {
        self.tabBarItem.badgeValue = strCount;
    }else{
        self.tabBarItem.badgeValue = nil;

    }
        NSLog(@"self.tabBarItem.badgeValue==============%@",self.tabBarItem.badgeValue);

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self requestgetCommonOpen];
    [self sendRequest];
    
    self.navigationController.navigationBar.barTintColor =Colorbackground;
    
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc]init] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc]init]];
    self.navigationController.navigationBar.translucent = NO;
    
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor blackColor], NSFontAttributeName : FontP(18)};

    
    
    
        [self.conversationListTableView reloadData];

    
 
}
- (void)outMassgUserInit{
    [self.conversationListTableView reloadData];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    // 设置在NavigatorBar中显示连接中的提示
    //    self.showConnectingStatusOnNavigatorBar = YES;
}
#pragma mark ============融云============
- (void)setHistoryNoticeModel {
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"messageId"] != nil) {
        HQMessage *message = [HQMessage new];
        
        message.messageId = [[NSUserDefaults standardUserDefaults] valueForKey:@"messageId"];
        message.noticeType = [[NSUserDefaults standardUserDefaults] valueForKey:@"noticeType"];
        
        message.noticeImg = [[NSUserDefaults standardUserDefaults] valueForKey:@"noticeImg"];
        message.title = [[NSUserDefaults standardUserDefaults] valueForKey:@"title"];
        message.createTime = [[NSUserDefaults standardUserDefaults] valueForKey:@"createTime"];
        
        RCConversationModel *conversationModel = [RCConversationModel new];
        conversationModel.extend = message;
        conversationModel.targetId = @"Notice";
        conversationModel.unreadMessageCount = 0;
        conversationModel.conversationType = ConversationType_PRIVATE;
        conversationModel.conversationModelType = RC_CONVERSATION_MODEL_TYPE_CUSTOMIZATION;
        
        self.noticeModel = conversationModel;
    }
    
    
}
//创建
- (void)getNotice {
    __weak typeof(&*self) __blockSelf = self;
    RCConversationModel *conversationModel = [RCConversationModel new];
    conversationModel.conversationModelType = RC_CONVERSATION_MODEL_TYPE_CUSTOMIZATION;
    [RCDHTTPTOOL getFirstNotificationByUid:[HQHttpManager getUserId]
                                     token:[HQHttpManager getUserToken]
                         successCompletion:^(HQMessage *model) {
                             if (model) {
                                 NSString *msgId = [[NSUserDefaults standardUserDefaults] valueForKey:@"messageId"];
                                 if ([msgId isEqualToString:model.messageId]) {
                                     
                                     conversationModel.extend = model;
                                     conversationModel.targetId = @"Notice";
                                     conversationModel.unreadMessageCount = 0;
                                     conversationModel.conversationType = ConversationType_PRIVATE;
                                     conversationModel.conversationModelType = RC_CONVERSATION_MODEL_TYPE_CUSTOMIZATION;
                                     return ;
                                 } else {
                                     [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"messageId"];
                                     [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"noticeType"];
                                     [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"title"];
                                     [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"createTime"];
                                     [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"noticeImg"];
                                     
                                     [[NSUserDefaults standardUserDefaults] setValue:model.messageId forKey:@"messageId"];
                                     [[NSUserDefaults standardUserDefaults] setValue:model.noticeType forKey:@"noticeType"];
                                     [[NSUserDefaults standardUserDefaults] setValue:model.title forKey:@"title"];
                                     [[NSUserDefaults standardUserDefaults] setValue:model.createTime forKey:@"createTime"];
                                     [[NSUserDefaults standardUserDefaults] setValue:model.noticeImg forKey:@"noticeImg"];
                                     [[NSUserDefaults standardUserDefaults] synchronize];
                                     
                                     conversationModel.extend = model;
                                     conversationModel.targetId = @"Notice";
                                     conversationModel.unreadMessageCount = 1;
                                     conversationModel.conversationType = ConversationType_PRIVATE;
                                     conversationModel.conversationModelType = RC_CONVERSATION_MODEL_TYPE_CUSTOMIZATION;
                                     
                                 }
                                 dispatch_async(dispatch_get_main_queue(), ^{
                                     self.noticeModel = nil;
                                     self.noticeModel = conversationModel;
                                     [__blockSelf refreshConversationTableViewWithConversationModel:conversationModel];
                                     [self notifyUpdateUnreadMessageCount];
                                     
                                 });
                             }
                             
                         }];

}
#pragma mark ===============跳转到通讯录=============
- (void)clickRitghButton {
    SDContactsTableViewController *CTVC = [[SDContactsTableViewController alloc] init];
    [self.navigationController pushViewController:CTVC animated:YES];
}

- (void)requestgetCommonOpen{
    WEAKSELF
    [HcardHttpmanager getCommonOpen:[HQHttpManager getUserId] success:^(id result) {
        if([result[@"code"] isEqualToString:@"ok"]){
            
            _UserTypehidden = result[@"res"][@"open"];
            [weakSelf headViewdateDidLoad];
            weakSelf.conversationListTableView.tableHeaderView = _headView;

            [weakSelf.conversationListTableView reloadData];
        }
        
    } failure:^(NSError *error) {
        
    }];
    
}

- (void)headViewdateDidLoad {
    
    if (!_headView) {
        
        CGFloat cellH ;
        if ([_UserTypehidden isEqualToNumber:@1]) {
            cellH = 67*2;
            

        }else{
            cellH = 67;
            

        }
        
    
        _headView = [[UIView alloc] init];
        
        _headView.backgroundColor = [UIColor whiteColor];
        _headView.frame = CGRectMake(0, 0, KScreenWidth, cellH);
        
  
        
        RCDChatListCell *cell = [[RCDChatListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"friend"];
        cell.frame = CGRectMake(0, 0, KScreenWidth, 67);
        
        cell.ivAvaImageType = @"0";
        
        cell.lblName.text = @"好友动态";
        cell.lblDetail.hidden = YES;
        cell.myBadgeLabel.hidden = YES;
        cell.model = nil;
//        cell.ivAva.backgroundColor = ColorI(0x039758);
        cell.ivAvaone.image = [UIImage imageNamed:@"message_friend_button"];
        cell.ivAvaImage.image = [UIImage imageNamed:@"message_friend_circle_icon"];
        
        UIImageView *friendImage = [[UIImageView alloc] init];
        friendImage.frame = CGRectMake(KScreenWidth-82, 15, 36, 36);
        friendImage.layer.cornerRadius = 18;
        friendImage.layer.masksToBounds = YES;
        
        if (_mfDic[@"photo"]) {
            [friendImage sd_setImageWithURL:[NSURL URLWithString:HttpImgUrl(_mfDic[@"photo"])]];
            
        }
        [cell addSubview:friendImage];
        
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"jiantou2"]];
        imageView.frame = CGRectMake(KScreenWidth-40, 23, 18, 18);
        [cell addSubview:imageView];
        [_headView addSubview:cell];
        NSNumber *friendNumberCount = _mfDicCount[@"count"];
        
        UILabel *friendCount = [[UILabel alloc] init];
        friendCount.frame = CGRectMake(imageView.left-21, 24, 16, 16);
        friendCount.textAlignment = NSTextAlignmentCenter;
        friendCount.font = [UIFont systemFontOfSize:12];
        friendCount.backgroundColor = [UIColor redColor];
        friendCount.textColor = [UIColor whiteColor];
        friendCount.layer.cornerRadius = 8;
        friendCount.layer.masksToBounds = YES;
        [cell addSubview:friendCount];
        
        friendCount.text = friendNumberCount.stringValue;
        _friendCount = friendCount;
        if (friendNumberCount.integerValue != 0) {
            friendCount.hidden = NO;
            
        } else {
            friendCount.hidden = YES;
            
        }
        
        UILabel *linLab = [[UILabel alloc] initWithFrame:CGRectMake(10, cell.bottom, KScreenWidth-10, 1)];
        linLab.backgroundColor = TheLinColor;
        [cell addSubview: linLab];
        
        
        /*********************************************/
        RCDChatListCell *cell2 = [[RCDChatListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"friend"];
        cell2.frame = CGRectMake(0, 67, KScreenWidth, 67);
        cell2.lblName.text = @"谁喜欢我";
//        cell2.ivAva.backgroundColor = ColorI(0xff4e56);
        cell2.ivAvaone.image = [UIImage imageNamed:@"message_who_like_button"];
        cell2.ivAvaImage.image = [UIImage imageNamed:@"message_who_like_icon"];
        cell2.ivAvaImageType = @"1";
        cell2.lblDetail.hidden = YES;
        cell2.myBadgeLabel.hidden = YES;
        NSNumber *count = _mfDic[@"wooCount"];
        
        
        UIImageView *likeImage = [[UIImageView alloc] init];
        likeImage.frame = CGRectMake(KScreenWidth-82, 15, 36, 36);
        likeImage.layer.cornerRadius = 18;
        likeImage.layer.masksToBounds = YES;
        if (_mfDic[@"giftImg"]) {
            [likeImage sd_setImageWithURL:[NSURL URLWithString:HttpImgUrl(_mfDic[@"giftImg"])]];
        }
        [cell2 addSubview:likeImage];
        
        UIImageView *imageView2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"jiantou2"]];
        imageView2.frame = CGRectMake(KScreenWidth-40, 23, 18, 18);
        UILabel *countLabel = [[UILabel alloc] init];
        countLabel.frame = CGRectMake(imageView2.left-21, 24, 16, 16);
        countLabel.textAlignment = NSTextAlignmentCenter;
        countLabel.font = [UIFont systemFontOfSize:12];
        countLabel.backgroundColor = [UIColor redColor];
        countLabel.textColor = [UIColor whiteColor];
        countLabel.layer.cornerRadius = 8;
        countLabel.layer.masksToBounds = YES;
        [cell2 addSubview:countLabel];
        countLabel.text = count.stringValue;
        _countLabel = countLabel;
        
        if (count.integerValue != 0) {
            countLabel.hidden = NO;
        } else {
            countLabel.hidden = YES;
        }
        
        UILabel *linLabcell2 = [[UILabel alloc] initWithFrame:CGRectMake(10, 66, KScreenWidth-10, 1)];
        linLabcell2.backgroundColor = TheLinColor;
        [cell2 addSubview: linLabcell2];
        
        [cell2 addSubview:imageView2];
        [_headView addSubview:cell2];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickFriend)];
        tap.numberOfTapsRequired = 1; // 单击
        [cell addGestureRecognizer:tap];
        UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickLikeMe)];
        tap2.numberOfTapsRequired = 1; // 单击
        [cell2 addGestureRecognizer:tap2];
        _likeImageView = likeImage;
        _friendImage = friendImage;
        
        if ([_UserTypehidden isEqualToNumber:@1]) {
            cell2.hidden = NO;
            [self.conversationListTableView reloadData];
        }else{
            cell2.hidden = YES;
            [self.conversationListTableView reloadData];

        }
        
        
        
        
        
    }

}
#pragma mark =================headerView 点击===================
//跳转到朋友圈
- (void)clickFriend {


    FriendLineViewController *TLVC = [[FriendLineViewController alloc] init];
    TLVC.isFriend = YES;
    
    [self.navigationController pushViewController:TLVC animated:YES];

}
//谁喜欢我
- (void)clickLikeMe {
    FriendLikeMeViewController *LMVC = [[FriendLikeMeViewController alloc] init];
    LMVC.likeNumber = _mfDic[@"wooUpdateCount"];
    [self.navigationController pushViewController:LMVC animated:YES];
}

#pragma mark ================设置会话列表=============
- (void)setUpConversationTable {
    //无会话时候显示的背景
    UIView *backgroundView = [[UIView alloc]init];
    backgroundView.backgroundColor = RGB(253, 253, 253);
    self.emptyConversationView = backgroundView;
    self.conversationListTableView.tableFooterView = [UIView new];
    self.conversationListTableView.separatorColor = RGB(223, 223, 223);
    [self.conversationListTableView reloadData];
    
}

#pragma mark ================点击会话列表里===========
- (void)onSelectedTableRow:(RCConversationModelType)conversationModelType conversationModel:(RCConversationModel *)model atIndexPath:(NSIndexPath *)indexPath {
    if (conversationModelType == RC_CONVERSATION_MODEL_TYPE_NORMAL && model.conversationType == ConversationType_PRIVATE) {

        
        
        HQConversationViewController *conversationVC = [[HQConversationViewController alloc]init];
        conversationVC.conversationType = model.conversationType;
        conversationVC.targetId = model.targetId;
        conversationVC.title = model.conversationTitle;
        conversationVC.conversation = model;


        
        [[RCIMClient sharedRCIMClient] clearMessagesUnreadStatus:ConversationType_PRIVATE targetId:model.targetId];
        model.unreadMessageCount = 0;
        conversationVC.unReadMessage = model.unreadMessageCount;
        conversationVC.hidesBottomBarWhenPushed = YES;
        conversationVC.pushViewController = ^(NSString *deleteId) {
            [[RCIMClient sharedRCIMClient] removeConversation:ConversationType_PRIVATE targetId:deleteId];
        };
        
        NSString *Str = @"KNOTIFICATION_ReceiveMessage";
        [[NSNotificationCenter defaultCenter] postNotificationName:Str object:nil];
        [self.navigationController pushViewController:conversationVC animated:YES];
    }
    if (conversationModelType == RC_CONVERSATION_MODEL_TYPE_CUSTOMIZATION &&model.conversationType == ConversationType_PRIVATE) {
        //        self.noticeModel.unreadMessageCount = 0;
        //        HQNoticeViewController *noticeVC = kVCFromSb(@"HQNoticeViewController", @"Message");
        //        HQMessage *message = model.extend;
        //        noticeVC.msgId = message.messageId;
        //        noticeVC.noticeType = message.noticeType;
        //        noticeVC.hidesBottomBarWhenPushed = YES;
        //        [self.navigationController pushViewController:noticeVC animated:YES];
    }
    if (model.conversationType == ConversationType_SYSTEM && [model.lastestMessage isMemberOfClass:[RCContactNotificationMessage class]]) {
        
        //        RCContactNotificationMessage *_contactNotificationMsg = (RCContactNotificationMessage *)model.lastestMessage;
        //        if ([_contactNotificationMsg.operation isEqualToString:@"add"]) {
        //#warning 点击跳转到新朋友界面
        //            HQFriendApplyViewController *applyVC = kVCFromSb(@"HQFriendApplyViewController", @"Buddy");
        //            applyVC.hidesBottomBarWhenPushed = YES;
        //            [self.navigationController pushViewController:applyVC animated:YES];
        //        }
    }
}

#pragma mark ==============插入自定义会话model=============

//插入自定义会话model
-(NSMutableArray *)willReloadTableData:(NSMutableArray *)dataSource {
    if (self.noticeModel) {
        [dataSource insertObject:self.noticeModel atIndex:0];
    }
    for (int i=0; i<dataSource.count; i++) {
        RCConversationModel *model = dataSource[i];
        //筛选请求添加好友的系统消息，用于生成自定义会话类型的cell
        if(model.conversationType == ConversationType_SYSTEM && [model.lastestMessage isMemberOfClass:[RCContactNotificationMessage class]]) {
            model.conversationModelType = RC_CONVERSATION_MODEL_TYPE_CUSTOMIZATION;
            
            
        }
    }
    return dataSource;
}

- (void)didDeleteConversationCell:(RCConversationModel *)model {
    [[RCIMClient sharedRCIMClient] clearMessages:ConversationType_PRIVATE targetId:model.targetId];
    NSInteger count = [[RCIMClient sharedRCIMClient] getTotalUnreadCount];
    if (count > 0) {
        self.tabBarItem.badgeValue = @(count).stringValue;
    }else{
        self.tabBarItem.badgeValue = nil;
    }
}

//左滑删除
-(void)rcConversationListTableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    //可以从数据库删除数据
    RCConversationModel *model = self.conversationListDataSource[indexPath.row];
    [[RCIMClient sharedRCIMClient] removeConversation:ConversationType_SYSTEM targetId:model.targetId];
    [[RCIMClient sharedRCIMClient] clearMessages:ConversationType_PRIVATE targetId:model.targetId];
    if ([model.targetId isEqualToString:@"Notice"]) {
        self.noticeModel = nil;
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"messageId"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"noticeType"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"title"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"createTime"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"noticeImg"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    

    [self.conversationListDataSource removeObjectAtIndex:indexPath.row];
    [self.conversationListTableView reloadData];
}

//高度
-(CGFloat)rcConversationListTableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 67.0f;
}

- (void)refreshConversationTableViewWithConversationModel:(RCConversationModel *)conversationModel {
    conversationModel.conversationModelType = RC_CONVERSATION_MODEL_TYPE_CUSTOMIZATION;
    [super refreshConversationTableViewWithConversationModel:conversationModel];
}

- (RCConversationBaseCell *)rcConversationListTableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    RCConversationModel *model = self.conversationListDataSource[indexPath.row];
    if(model.conversationType == ConversationType_SYSTEM && [model.lastestMessage isMemberOfClass:[RCContactNotificationMessage class]]) {
        RCContactNotificationMessage *_contactNotificationMsg = (RCContactNotificationMessage *)model.lastestMessage;
        if ([_contactNotificationMsg.operation isEqualToString:@"add"]) {
            RCDChatListCell *cell = [[RCDChatListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
            //            cell.lblName.text = _contactNotificationMsg.message;
            cell.lblDetail.text = [NSString stringWithFormat:@"来自%@的好友请求",_contactNotificationMsg.message];
            cell.labelTime.text = [self ConvertMessageTime:model.sentTime / 1000];
            
            [cell.ivAva sd_setImageWithURL:[NSURL URLWithString:_contactNotificationMsg.extra] placeholderImage:[UIImage imageNamed:@"icon_person"]];
            cell.lblName.text = @"好友请求";
            cell.myBadgeLabel.hidden = YES;
            return cell;
        }
        if ([_contactNotificationMsg.operation isEqualToString:@"deal"]) {
            RCDChatListCell *cell = [[RCDChatListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
            //            cell.lblName.text = _contactNotificationMsg.message;
            cell.lblDetail.text = [NSString stringWithFormat:@"%@已添加你为好友",_contactNotificationMsg.message];
            cell.labelTime.text = [self ConvertMessageTime:model.sentTime / 1000];
            
            [cell.ivAva sd_setImageWithURL:[NSURL URLWithString:_contactNotificationMsg.extra] placeholderImage:[UIImage imageNamed:@"icon_person"]];
            cell.lblName.text = @"好友通知";
            cell.myBadgeLabel.hidden = YES;
            return cell;
        }
    } else {
        RCDChatListCell *cell = [[RCDChatListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
        
        HQMessage *message = model.extend;
        cell.lblDetail.text = message.title;
        [cell.ivAva  sd_setImageWithURL:[NSURL URLWithString:message.noticeImg] placeholderImage:[UIImage imageNamed:@""]];
        cell.labelTime.text = message.createTime;
        cell.lblName.text = @"通知";
        cell.model = model;
        if (model.unreadMessageCount) {
            cell.myBadgeLabel.hidden = NO;
        } else {
            cell.myBadgeLabel.hidden = YES;
        }
        return cell;
    }
    return nil;
}
#pragma mark - ===========private============
- (NSString *)ConvertMessageTime:(long long)secs {
    NSString *timeText = nil;
    NSDate *messageDate = [NSDate dateWithTimeIntervalSince1970:secs];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *strMsgDay = [formatter stringFromDate:messageDate];
    NSDate *now = [NSDate date];
    NSString *strToday = [formatter stringFromDate:now];
    NSDate *yesterday = [[NSDate alloc] initWithTimeIntervalSinceNow:-(24 * 60 * 60)];
    NSString *strYesterday = [formatter stringFromDate:yesterday];
    NSString *_yesterday = nil;
    if ([strMsgDay isEqualToString:strToday]) {
        [formatter setDateFormat:@"HH':'mm"];
    } else if ([strMsgDay isEqualToString:strYesterday]) {
        _yesterday = NSLocalizedStringFromTable(@"Yesterday", @"RongCloudKit", nil);
    }
    if (nil != _yesterday) {
        timeText = _yesterday;
    } else {
        timeText = [formatter stringFromDate:messageDate];
    }
    return timeText;
}

#pragma mark - 收到消息监听
- (void)didReceiveMessageNotification:(NSNotification *)notification {
    __weak typeof(&*self) blockSelf_ = self;
    //处理好友请求
    RCMessage *message = notification.object;
    //NSLog(@"message=%@",notification.object);
    if ([message.content isMemberOfClass:[RCContactNotificationMessage class]]) {
        RCContactNotificationMessage *_contactNotificationMsg = (RCContactNotificationMessage *)message.content;
        RCConversationModel *customModel = [RCConversationModel new];
        customModel.conversationModelType = RC_CONVERSATION_MODEL_TYPE_CUSTOMIZATION;
        customModel.lastestMessage = _contactNotificationMsg;
        dispatch_async(dispatch_get_main_queue(), ^{
            [blockSelf_ refreshConversationTableViewWithConversationModel:customModel];
            [self notifyUpdateUnreadMessageCount];
            NSNumber *left = [notification.userInfo objectForKey:@"left"];
            if (0 == left.integerValue) {
                [super refreshConversationTableViewIfNeeded];
            }
        });
    } else if ([message.content isMemberOfClass:[RCMessageContent class]]) {
        RCMessageContent *_contactNotificationMsg = message.content;
        RCConversationModel *customModel = [RCConversationModel new];
        customModel.conversationModelType = RC_CONVERSATION_MODEL_TYPE_CUSTOMIZATION;
        customModel.lastestMessage = _contactNotificationMsg;
        dispatch_async(dispatch_get_main_queue(), ^{
            [blockSelf_ refreshConversationTableViewWithConversationModel:customModel];
            [self notifyUpdateUnreadMessageCount];
            NSNumber *left = [notification.userInfo objectForKey:@"left"];
            if (0 == left.integerValue) {
                [super refreshConversationTableViewIfNeeded];
            }
        });
    } else if ([message.content isMemberOfClass:[RCInformationNotificationMessage class]]) {
        RCInformationNotificationMessage *_contactNotificationMsg = (RCInformationNotificationMessage *)message.content;
        if ([_contactNotificationMsg.message isEqualToString:@"对方已经删除了你"]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [[RCIMClient sharedRCIMClient] removeConversation:ConversationType_PRIVATE targetId:message.targetId];
                [[RCIMClient sharedRCIMClient] clearMessages:ConversationType_PRIVATE targetId:message.targetId];
                //                for (RCConversationModel *model in self.conversationListDataSource) {
                //                    if ([model.targetId isEqualToString:message.targetId]) {
                //                        [self.conversationListDataSource removeObject:model];
                //
                //                    }
                //                }
                //                [self.conversationListTableView reloadData];
                [super refreshConversationTableViewIfNeeded];
            });
        }
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            [super didReceiveMessageNotification:notification];

        });

    }
    
    
    [self.conversationListTableView reloadData];

}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - =================定位==================
- (void)didLocation{
    if ([CLLocationManager locationServicesEnabled]) {
        //定位功能可用，开始定位
        self.locationManger = [[CLLocationManager alloc] init];
        self.locationManger.delegate = self;
        if ([[[UIDevice currentDevice] systemVersion] floatValue]  >= 8.0) {
            //使用期间
            [self.locationManger requestWhenInUseAuthorization];
            //始终
            
        }
        [self.locationManger startUpdatingLocation];
    }else{
        
    }
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
            if ([self.locationManger respondsToSelector:@selector(requestAlwaysAuthorization)]) {
                [self.locationManger requestWhenInUseAuthorization];
            }
            break;
        default:
            break;
    }
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"error");
    //[[DMCAlertCenter defaultCenter] postAlertWithMessage:@"定位失败，请重新定位"];
}

// 6.0 以上调用这个函数
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    CLLocation *newLocation = locations[0];
    CLLocationCoordinate2D oldCoordinate = newLocation.coordinate;
    longitude = oldCoordinate.longitude;
    latitude = oldCoordinate.latitude;
    NSLog(@"旧的经度：%f,旧的纬度：%f",oldCoordinate.longitude,oldCoordinate.latitude);
    [self.locationManger stopUpdatingLocation];
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:newLocation
                   completionHandler:^(NSArray *placemarks, NSError *error){
                       for (CLPlacemark *placeMark in placemarks) {
                           NSDictionary *addressDic = placeMark.addressDictionary;
//                           NSString *state=[addressDic objectForKey:@"State"];
                           NSString *city=[addressDic objectForKey:@"City"];
//                           NSString *subLocality=[addressDic objectForKey:@"SubLocality"];
//                           NSString *street=[addressDic objectForKey:@"Street"];
                           [HQHttpManager putLocationWithUid:[HQHttpManager getUserId] lon:@(longitude) lat:@(latitude) location:[NSString stringWithFormat:@"%@",city] successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
                               
                           }];
                       }
                   }];
    [[NSUserDefaults standardUserDefaults] setObject:@(longitude).stringValue forKey:@"longitude"];
    [[NSUserDefaults standardUserDefaults] setObject:@(latitude).stringValue forKey:@"latitude"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
#pragma mark ====================网络请求================
- (void)sendRequest {
    [HQHttpManager mfWithCount:[HQHttpManager getUserId] successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
        if (isSuccess) {
            _mfDicCount = resultDic;
            [self.conversationListTableView reloadData];

            NSNumber *friendCount = _mfDicCount[@"count"];
            _friendCount.text = friendCount.stringValue;

            
            NSString *str  = [NSString stringWithFormat:@"%@", _mfDic[@"status"]];
            
            if ([str isEqualToString:@"1"]) {
                if (friendCount.integerValue == 0) {
                    [self.friendImage sd_setImageWithURL:[NSURL URLWithString:HttpImgUrl(_mfDic[@"photo"])]];
                    _friendImage.hidden = NO;
                }else{
                    _friendImage.hidden = YES;
                }
                
            }else{
                self.friendImage.image = [UIImage imageNamed:@""];
            }
            
            if (friendCount.integerValue != 0) {
                _friendCount.hidden = NO;
                _friendImage.hidden = YES;
            } else {
                _friendCount.hidden = YES;
                _friendImage.hidden = NO;
                
            }
            
        }
    }];

    
    
    
    [HQHttpManager mfWithUid:[HQHttpManager getUserId] successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
        if (isSuccess) {
            _mfDic = resultDic;
            [self.conversationListTableView reloadData];
        
            
            
            NSNumber *count = _mfDic[@"wooUpdateCount"];
            _countLabel.text = count.stringValue;
            
            if (count.integerValue != 0) {
                _countLabel.hidden = NO;
            } else {
                _countLabel.hidden = YES;
            }
            
        }
        

        
    }];
    

}
@end
